package com.example.blog.service.impl;

import com.example.blog.dao.CommentDao;
import com.example.blog.dto.ArticleDTO;
import com.example.blog.dto.CommentDTO;
import com.example.blog.pojo.PageBean;
import com.example.blog.service.CommentService;
import com.example.blog.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;

    @Override
    public PageBean<CommentDTO> getlistbyarticleid(Integer pageNum,
                                                   Integer pageSize,Integer articleid) {
        //1.创建PageBean对象
        PageBean<CommentDTO> pb = new PageBean<>();

        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);

        //3.调用mapper
//        Map<String,Object> map = ThreadLocalUtil.get();
//        Integer userId = (Integer) map.get("id");
        List<CommentDTO> as = commentDao.findCommentByarticleid(articleid);
        //Page中提供了方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<CommentDTO> p = (Page<CommentDTO>) as;

        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public List<CommentDTO> getlistbyuserid() {

        //获取当前用户id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        List<CommentDTO> list = commentDao.findCommentByuserid(userid);
        return list;

    }

    @Override
    public boolean addcomment(Integer articleid, String content) {

        //获取当前用户id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        Integer n = commentDao.addComment(userid,articleid,content, LocalDateTime.now());
        if( n>0 )return true;
        else return false;

    }

    @Override
    public boolean deletecomment(Integer id, Integer userid) {

        Integer n = commentDao.deleteById(id, userid);
        if(n>0)return true;
        else return false;

    }
}
